#include "platform.h"

#define MAX_WATE_TIME 0xA000
#define MAX_ACK_TIME  0xA00

int i2c_writebuffer(uint8_t devAddr,const uint8_t *buf,int len)
{
	int i=0;
	int times;
	uint8_t err = I2C_Err_No;
	
	//check the bus if busy
	times=MAX_WATE_TIME;
	while(I2C_GetFlagStatus(I2C, I2C_FLAG_BUSY)==SET)
	{
		if((times--)==0){
			err = I2C_Err_BusBusy;
			goto stop;
		}
	}
	
	I2C_TransferHandling(I2C,devAddr,len,
		I2C_AutoEnd_Mode,I2C_Generate_Start_Write);
	
	//send data 
	while(i<len)
	{
		times = MAX_WATE_TIME;
		while(I2C_GetFlagStatus(I2C, I2C_FLAG_TXIS)==RESET){
			if( (times--)==0 ){
				err = I2C_Err_SendData;
				goto stop;
			}
		}
		I2C_SendData(I2C, buf[i++]);
	}
	
	stop:
	//wating stop flag
	times=MAX_WATE_TIME;
	while(I2C_GetFlagStatus(I2C,I2C_FLAG_STOPF)==RESET) {
		if( (times--) ==0){
			break;
		}
	}
	I2C_ClearFlag(I2C,I2C_ICR_STOPCF);
	
	//check if recive NACK
	if(I2C_GetFlagStatus(I2C,I2C_FLAG_NACKF)==SET)
	{
		err=I2C_Err_SendDevAddr;
		I2C_ClearFlag(I2C,I2C_FLAG_NACKF);
	}

	return err;
}

int i2c_readbuffer(uint8_t devAddr,uint8_t *buf,int len)
{
	int i=0,times;
	uint8_t err = I2C_Err_No;
	
	//check the bus if busy
	times=MAX_WATE_TIME;
	while(I2C_GetFlagStatus(I2C, I2C_FLAG_BUSY)==SET)
	{
		if((times--)==0){
			err = I2C_Err_BusBusy;
			goto stop;
		}
	}
	
	//Generate start
	I2C_TransferHandling(I2C,devAddr,len,
		I2C_AutoEnd_Mode,I2C_Generate_Start_Read);
	
	for(i=0;i<len;i++)
	{
		times=MAX_WATE_TIME;
		while(I2C_GetFlagStatus(I2C, I2C_FLAG_RXNE)==RESET)
		{
			if((times--)==0){
				err = I2C_Err_ReadData;
				goto stop;
			}
		}
		buf[i]=I2C_ReceiveData(I2C);
	}
	
	stop:
	
	times=MAX_WATE_TIME;
	while(I2C_GetFlagStatus(I2C,I2C_FLAG_STOPF)==RESET)
	{
		if((times--)==0){
			break;
		}
	}
	I2C_ClearFlag(I2C, I2C_ICR_STOPCF);
	
	//check if recive NACK
	if(I2C_GetFlagStatus(I2C,I2C_FLAG_NACKF)==SET)
	{
		err=I2C_Err_SendDevAddr;
		I2C_ClearFlag(I2C,I2C_FLAG_NACKF);
	}
	
	return err;
}

